package cn.jksoft.businessclient.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingApi;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseActivity;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseSwipeBackCompatActivity;
import cn.jksoft.businessclient.bean.BaseEntity;
import cn.jksoft.businessclient.bean.CheckOrderEntity;
import cn.jksoft.businessclient.bean.OrderDetailStatusEntity;
import cn.jksoft.businessclient.bean.ProductEntity;
import cn.jksoft.businessclient.bean.StoreServiceEntity;
import cn.jksoft.businessclient.ui.adapter.FragmentAdapter;
import cn.jksoft.businessclient.ui.adapter.ProductSelectExpandableAdapter;
import cn.jksoft.businessclient.ui.fragment.CreateOrderProductFragment;
import cn.jksoft.businessclient.ui.fragment.CreateOrderServiceFragment;
import cn.jksoft.businessclient.utils.CommonUtils;
import cn.jksoft.businessclient.utils.DensityUtils;
import cn.jksoft.businessclient.utils.DialogHelp;
import cn.jksoft.businessclient.widgets.BadgeView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by RogersHuang on 16/4/12.
 */
public class CreateOrderActivity extends BaseSwipeBackCompatActivity implements View.OnClickListener {

    private static final int REQUEST_SELECT_CUSTOMER = 1000;

    @Bind(R.id.tv_car_plate_num)
    TextView tvCarPlateNum;
    @Bind(R.id.tv_total_price)
    TextView tvTotalPrice;
    @Bind(R.id.tv_submit_order)
    TextView submitOrderBtn;
    @Bind(R.id.iv_shopping_car)
    ImageView ivShoppingCar;
    @Bind(R.id.ll_bottom)
    RelativeLayout llBottom;

    @Bind(R.id.tabs)
    TabLayout mTabLayout;

    @Bind(R.id.viewpager)
    ViewPager mViewPager;

    private CreateOrderServiceFragment serviceFragment;
    private CreateOrderProductFragment productFragment;
    private View rootview;
    private PopupWindow popupServiceItem;
    private LinearLayout popListLayout;
    private BadgeView mBvNotice;
    private ProductSelectExpandableAdapter selectAdapter;
    private ProgressDialog waitDialog;
    private List<List<ProductEntity>> selectAllArray;
    private List<List<String>> selectProductIdArray;
    List<String> groups = new ArrayList<String>();
    private int totalPrice;
    private long customerId,custCmId;
    private String customerName;

    private boolean isExistOrder;
    private long outboundId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_billing);
        ButterKnife.bind(this);
        initTitle("开单");
        initBackClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initFragments();
        initViewPager();
        initView();
        if(getIntent().getBooleanExtra("isAddOrder",false)){
            custCmId = getIntent().getLongExtra("CUST_CM_ID",-1);
            customerId = getIntent().getLongExtra("CUSTOMER_ID",-1);
            customerName = getIntent().getStringExtra("CUSTOMER_NAME");
            tvCarPlateNum.setText(getIntent().getStringExtra("CAR_PLATE_NUM"));
        }
        outboundId = getIntent().getLongExtra("outboundId",-1);
    }

    private void initFragments() {
        serviceFragment = new CreateOrderServiceFragment();
        productFragment = new CreateOrderProductFragment();
    }

    private void initViewPager() {
        ArrayList<String> titles = new ArrayList<>();
        titles.add("服务");
        titles.add("产品");
        for(int i=0;i<titles.size();i++){
            mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(i)));
        }
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(serviceFragment);
        fragments.add(productFragment);
        FragmentAdapter mFragmentAdapteradapter =
                new FragmentAdapter(getSupportFragmentManager(), fragments, titles);
        mViewPager.setAdapter(mFragmentAdapteradapter);
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabsFromPagerAdapter(mFragmentAdapteradapter);
        mViewPager.setCurrentItem(0);
    }

    private void initView() {
        groups.add("服务");
        groups.add("产品");
        selectAllArray = new ArrayList<List<ProductEntity>>();
        selectAllArray.add(new ArrayList<ProductEntity>());
        selectAllArray.add(new ArrayList<ProductEntity>());
        selectProductIdArray = new ArrayList<List<String>>();
        selectProductIdArray.add(new ArrayList<String>());
        selectProductIdArray.add(new ArrayList<String>());
        waitDialog = DialogHelp.getWaitDialog(this, "正在下单，请稍后...");
        mBvNotice = new BadgeView(CreateOrderActivity.this, ivShoppingCar);
        mBvNotice.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
        mBvNotice.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        mBvNotice.setBackgroundResource(R.drawable.notification_bg);
        mBvNotice.setGravity(Gravity.CENTER);
        serviceFragment.setSelectServiceListener(new CreateOrderServiceFragment.SelectServiceListener() {
            @Override
            public void didSelectService(ProductEntity entity) {
                addEntity(entity,0,false);
            }
        });

        productFragment.setSelectProductListener(new CreateOrderProductFragment.SelectProductListener() {
            @Override
            public void didSelectProduct(ProductEntity entity) {
                addEntity(entity,1,true);
            }
        });

        RxView.clicks(submitOrderBtn)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Object o) {
                        createOrder();
                    }
                });

    }

    private void addEntity(ProductEntity entity,int position,boolean isProduct){
        if (!selectProductIdArray.get(position).contains(entity.getPROD_SKU_ID())) {
            selectProductIdArray.get(position).add(entity.getPROD_SKU_ID());
            totalPrice = totalPrice + Integer.parseInt(entity.getSALE_PRICE());
            tvTotalPrice.setText("￥" + (double) totalPrice / 100);
            tvTotalPrice.setTextColor(getResources().getColor(R.color.red));
            ivShoppingCar.setImageResource(R.drawable.ic_shop_car_red);
            submitOrderBtn.setBackgroundColor(getResources().getColor(R.color.main_red));
            selectAllArray.get(position).add(entity);
        } else {
            if(isProduct) {
                showToast("您已添加该产品");
            }else{
                showToast("您已添加该服务");
            }
//                    totalPrice = totalPrice - entity.getSALE_PRICE();
//                    tvTotalPrice.setText("￥" + (double) totalPrice / 100);
//                    selectAllArray.get(0).remove(entity);
        }

        if (selectAllArray.size() > 0) {
            mBvNotice.setText(String.valueOf(selectAllArray.get(0).size()+selectAllArray.get(1).size()));
            mBvNotice.show();
        } else {
            mBvNotice.setText("");
            mBvNotice.hide();
            totalPrice = 0;
            tvTotalPrice.setText(null);
            ivShoppingCar.setImageDrawable(getResources().getDrawable(R.drawable.ic_shop_car_gray));
            submitOrderBtn.setBackgroundColor(getResources().getColor(R.color.main_light_gray));
        }
    }




    private void initPopup() {

        if (rootview == null) {
            rootview = getLayoutInflater().inflate(R.layout.popup_service_recyclerview, null);
        }
        // 创建PopupWindow对象
        int listHeight = DensityUtils.dip2px(this, 45 * (selectAllArray.get(0).size()+selectAllArray.get(1).size() >6  ? 6 : selectAllArray.get(0).size()+selectAllArray.get(1).size()) + 30*3+45);
        popupServiceItem = new PopupWindow(rootview, ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.getDisplayHeight(this)- CommonUtils.getToolbarHeight(this)-DensityUtils.getStatusBarHeight(this));
        popupServiceItem.setAnimationStyle(R.style.shopping_car_animstyle);
        //设置PopupWindow弹出窗体的背景
        popupServiceItem.setBackgroundDrawable(new BitmapDrawable());
        popupServiceItem.setOutsideTouchable(true);// 以及下一句 同时写才会有效
        popupServiceItem.setFocusable(true);// 获取焦点
        popListLayout = (LinearLayout)rootview.findViewById(R.id.listView_layout);
        LinearLayout llClearService = (LinearLayout) rootview.findViewById(R.id.ll_clear_service);
        ImageView ivEmpty = (ImageView)rootview.findViewById(R.id.iv_empty);
        ivEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupServiceItem.dismiss();
            }
        });
        ExpandableListView mListView = (ExpandableListView) rootview.findViewById(R.id.product_select_expandable_list);
        selectAdapter = new ProductSelectExpandableAdapter(this,groups,selectAllArray);
        mListView.setAdapter(selectAdapter);

        selectAdapter.setDeleteClickListener(new ProductSelectExpandableAdapter.OnDeleteClickListener() {
            @Override
            public void OnClickListener(View view, int groupPosition, int childPosition) {
                int price = Integer.parseInt(selectAllArray.get(groupPosition).get(childPosition).getSALE_PRICE());
                if (selectAllArray.get(0).size()+selectAllArray.get(1).size()>0) {
                    totalPrice = totalPrice - price;
                    tvTotalPrice.setText("￥" + (double) totalPrice / 100);
                    ProductEntity entity = (ProductEntity)selectAdapter.getChild(groupPosition,childPosition);
                    selectAllArray.get(groupPosition).remove(entity);
                    selectProductIdArray.get(groupPosition).remove(entity.getPROD_SKU_ID());
                    mBvNotice.setText(String.valueOf(selectAllArray.get(0).size()+selectAllArray.get(1).size()));
                    mBvNotice.show();
                    if(selectAllArray.get(0).size()+selectAllArray.get(1).size() > 0) {
                        updatePopView();
                    }else{
                        mBvNotice.setText("");
                        mBvNotice.hide();
                        totalPrice = 0;
                        tvTotalPrice.setText(null);
                        ivShoppingCar.setImageResource(R.drawable.ic_shop_car_gray);
                        submitOrderBtn.setBackgroundResource(R.color.main_light_gray);
                        popupServiceItem.dismiss();
                    }
                }
            }
        });
        llClearService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBvNotice.setText("");
                mBvNotice.hide();
                totalPrice = 0;
                tvTotalPrice.setText(null);
                ivShoppingCar.setImageDrawable(getResources().getDrawable(R.drawable.ic_shop_car_gray));
                submitOrderBtn.setBackgroundColor(getResources().getColor(R.color.main_light_gray));
                selectAllArray.get(0).clear();
                selectAllArray.get(1).clear();
                selectProductIdArray.get(0).clear();
                selectProductIdArray.get(1).clear();
                popupServiceItem.dismiss();
            }
        });
        int[] location = new int[2];
        llBottom.getLocationOnScreen(location);
        popListLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,listHeight));
        popupServiceItem.showAtLocation(llBottom, Gravity.BOTTOM, 0, 0);
        int groupCount= mListView.getCount();
        for (int i=0; i<groupCount; i++) {
            mListView.expandGroup(i);
        };
    }

    private void updatePopView() {
        selectAdapter.notifyDataSetChanged();
        int[] location = new int[2];
        llBottom.getLocationOnScreen(location);
        int popHeight = DensityUtils.dip2px(this, 45 * (selectAllArray.get(0).size()+selectAllArray.get(1).size() >6  ? 6 : selectAllArray.get(0).size()+selectAllArray.get(1).size()) + 30*3+45);
        popListLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,popHeight));
    }



    private void createOrder() {
        if(selectAllArray.get(0).size()+selectAllArray.get(1).size() == 0){
            return;
        }
        if (CommonUtils.isEmpty(customerName)) {
            showToast("请先选择客户");
            return;
        }
        JSONObject json = null;
        JSONArray jsonArr = null;
        try {
            json = new JSONObject();
            jsonArr = new JSONArray();

            int len = selectAllArray.size();
            if (len > 0) {
                for (int i = 0; i < len; i++) {
                    for (int j=0;j<selectAllArray.get(i).size();j++) {
                        ProductEntity entity = selectAllArray.get(i).get(j);
                        JSONObject serviceJson = new JSONObject();
                        serviceJson.put("prodSkuId", entity.getPROD_SKU_ID());
                        serviceJson.put("number", 1);
                        if(Long.parseLong((entity.getINVENTORY_ID()!=null && entity.getINVENTORY_ID().length()>0)?entity.getINVENTORY_ID():"-1")>0){
                            serviceJson.put("invertoryId", entity.getINVENTORY_ID());
                            serviceJson.put("storageId", entity.getSTORAGE_ID());
                        }
                        jsonArr.put(serviceJson);
                    }
                }
            } else {
                showToast("请至少选择一个服务下单");
                return;
            }

            waitDialog.show();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());
            json.put("prodSkuList", jsonArr);
            json.put("operId",BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
            if(getIntent().getBooleanExtra("isAddOrder",false) || isExistOrder){
                json.put("outboundId",outboundId);
            }else{
                json.put("tenantId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getTenantId());
                json.put("customerId", customerId);
                json.put("custCmId", custCmId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ReceivingApi service = ReceivingService.createReceivingService();
        if(getIntent().getBooleanExtra("isAddOrder",false) || isExistOrder){
            addOrder(service,json);
        }else {
            createNewOrder(service, json);
        }

    }

    private void createNewOrder(ReceivingApi service,JSONObject json){
        service.createMobileBillingOrder(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onCompleted() {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onNext(BaseEntity baseEntity) {
                        waitDialog.dismiss();
                        String retCode = baseEntity.getIs_successful();
                        if ("1".equals(retCode)) {
                            showToast(baseEntity.getResult());
                            Intent intent = new Intent();
                            intent.setClass(CreateOrderActivity.this, MainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
                            startActivity(intent);
                        } else {
                            showToast(baseEntity.getResult());
                        }
                    }
                });
    }

    private void addOrder(ReceivingApi service,JSONObject json){
        service.addOrder(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onCompleted() {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onNext(BaseEntity baseEntity) {
                        waitDialog.dismiss();
                        String retCode = baseEntity.getIs_successful();
                        if ("1".equals(retCode)) {
                            if(getIntent().getBooleanExtra("isAddOrder",false)){
                                Intent intent = getIntent();
                                setResult(RESULT_OK,intent);
                                finish();
                            }else {
                                showToast(baseEntity.getResult());
                                Intent intent = new Intent();
                                intent.setClass(CreateOrderActivity.this, MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
                                startActivity(intent);
                            }
                        } else {
                            showToast(baseEntity.getResult());
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_CUSTOMER) {
            if (resultCode == RESULT_OK && data != null) {
                custCmId = data.getExtras().getLong("custCmId");
                customerId = data.getExtras().getLong("customerId");
                customerName = data.getExtras().getString("customerName");
                tvCarPlateNum.setText(data.getExtras().getString("carPlateNum"));
                if(!getIntent().getBooleanExtra("isAddOrder",false)){
                    checkOrderExist();
                }
            }
        }
    }

    @Override
    @OnClick({R.id.ll_shopping_car, R.id.tv_submit_order, R.id.ll_service_billing})
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_shopping_car:
                if (selectAllArray.get(0).size()+selectAllArray.get(1).size() > 0) {
                    initPopup();
                }
                break;
            case R.id.ll_service_billing:
                if(!getIntent().getBooleanExtra("isAddOrder",false) || getIntent().getLongExtra("outboundId",-1)==-1) {
                    readyGoForResult(CustomerSelectActivity.class, REQUEST_SELECT_CUSTOMER);
                }else{
                    showToast("追加订单不能选择其他客户");
                }
                break;
            default:
                break;
        }
    }

    private void checkOrderExist() {

        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());
            json.put("customerId",customerId);
            json.put("custCmId",custCmId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.checkOrderExist(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CheckOrderEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(CheckOrderEntity entity) {

                        String retCode = entity.getIs_successful();
                        if ("1".equals(retCode)) {
                            if(entity.isFlag()){
                                showRemindDialog();
                            }
                            if(entity.getOrderInfo().getSERVICE_STATUS() == 0){
                                //服务中，下单时候状态为追加订单
                                isExistOrder = true;
                                outboundId = entity.getOrderInfo().getOUTBOUND_ID();
                            }

                        }
                    }
                });
    }

    private void showRemindDialog(){
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_order_remind_layout, null);
        final AlertDialog alertDialog =new AlertDialog.Builder(CreateOrderActivity.this).create();
        alertDialog.show();
        //关键在下面的两行,使用window.setContentView,替换整个对话框窗口的布局
        Window window = alertDialog.getWindow();
        window.setContentView(dialogView);
        Button btnClose = (Button)dialogView.findViewById(R.id.btn_close);
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

}
